package com.annotation.mvc.util;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CurrentServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		String action = request.getServletPath();
		ServletConfig config = this.getServletConfig();
		ServletContext context = this.getServletContext();
		Map<String, String> map = (Map<String, String>) context.getAttribute("setup");
		String value = map.get(action);
		String[] values = value.split("\\|\\|");
		String className = values[0];
		String methodName = values[1];
		String[] parameterName = values[2].split(",");
		Class<?>[] paras = new Class[parameterName.length];
		for (int i = 0; i < parameterName.length; i++) {
			try {
				paras[i] = Class.forName(parameterName[i]);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		Object objAction;
		Class<?> clazz;
		Object rs = null;
		try {
			clazz = Class.forName(className);
			objAction = clazz.newInstance();
			//get method
			Method method = clazz.getDeclaredMethod(methodName, paras);
			Object[] parasInstaces = new Object[paras.length];
			for (int i = 0; i < paras.length; i++) {
				Object paraInstance = null;
				paraInstance = (Object) paras[i].newInstance();
				Field[] fields = paras[i].getDeclaredFields();
				for (Field f : fields) {
					f.setAccessible(true);
					f.set(paraInstance, request.getParameter(f.getName()));
					f.setAccessible(false);
				}
				parasInstaces[i] = paraInstance;
			}
			rs = method.invoke(objAction, parasInstaces);
		} catch (Exception e) {
			e.printStackTrace();
		}
		RequestDispatcher dis = request.getRequestDispatcher(rs.toString());
		dis.forward(request, response);
	}
}
